/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  ClassDeclaration,
  ConstructorDeclaration,
  Decorator,
  InterfaceDeclaration,
  NewExpression,
  PropertyDeclaration,
  PropertySignature,
  SyntaxKind,
  TypeNode
} from 'ts-morph';
import {
  ClassAnalysis,
  ClassDecorators,
  ConstructorParam,
  DeserializationMode,
  GenericInfo,
  InheritanceInfo,
  InterfaceAnalysis,
  PropertyAnalysis,
  PropertyDecorators,
  PropertyKind,
  PropertyVisibility,
  SerializableOptions,
  TypeStructure
} from '../Types';
import { DecoratorConstants } from '../constants';
import { GenericTypeSubstitutionUtil } from '../utils/GenericTypeSubstitutionUtil';
import { TypeHandlerRegistry } from '../handlers';
import { CustomTypeAnalyzer } from './CustomTypeAnalyzer';
import { CustomError, ErrorCodes } from '../utils/CustomError';
import { Logger } from '../logger/Logger';
import { TsMorphUtil } from '../utils/TsMorphUtil';

export class ClassAnalyzer {
  /**
   * 分析类的完整结构，包括属性、构造函数、继承关系、装饰器等信息
   * @param classDecl 类声明节点
   * @returns 类分析结果
   */
  public static analyzeClass(classDecl: ClassDeclaration): ClassAnalysis {
    Logger.debug(`Analyzing class ${classDecl.wasForgotten()}`);
    const className = classDecl.getNameOrThrow(`Class name is undefined in ${classDecl.getSourceFile().getFilePath()}`);
    const sourceFilePath = classDecl.getSourceFile().getFilePath();
    Logger.warn(`Analyzing class ${className} ${sourceFilePath}`);

    const generics: GenericInfo = {
      isGeneric: classDecl.getTypeParameters().length > 0,
      parameters: classDecl.getTypeParameters().map((p) => p.getName())
    };
    // 分析继承信息
    const inheritance: InheritanceInfo = this.analyzeInheritanceInfo(classDecl);

    // 分析构造函数 - 传递继承信息
    const constructorParams: ConstructorParam[] = this.analyzeConstructorParameters(classDecl, inheritance);

    // 解析@Serializable注解的参数
    const decorators: ClassDecorators = {
      serializable: this.parseSerializableOptions(classDecl.getDecorator(DecoratorConstants.SERIALIZABLE)),
      serialName: this.parseSerialNameOptions(classDecl.getDecorator(DecoratorConstants.SERIAL_NAME))
    };

    // 分析自己的属性
    const ownProperties = this.analyzeOwnProperties(classDecl, constructorParams, generics.parameters);

    // 属性分类
    const propertyClassification = this.classifyProperties(ownProperties, inheritance, generics.parameters);

    return {
      className,
      sourceFilePath,
      originalClass: classDecl,
      generics,
      inheritance,
      decorators,
      ownProperties,
      inheritedProperties: propertyClassification.inheritedProperties,
      overriddenProperties: propertyClassification.overriddenProperties,
      properties: propertyClassification.properties,
      constructorParams
    };
  }

  /**
   * 分析接口的完整结构，包括属性、继承关系等信息
   * @param interfaceDecl 接口声明节点
   * @returns 接口分析结果
   */
  public static analyzeInterface(interfaceDecl: InterfaceDeclaration): InterfaceAnalysis {
    const interfaceName = interfaceDecl.getName();
    if (!interfaceName) {
      throw new CustomError(`Interface name is undefined in ${interfaceDecl.getSourceFile().getFilePath()}`,
        ErrorCodes.CLASS_DECLARATION_NOT_FOUND);
    }
    const sourceFilePath = interfaceDecl.getSourceFile().getFilePath();
    const generics: GenericInfo = {
      isGeneric: interfaceDecl.getTypeParameters().length > 0,
      parameters: interfaceDecl.getTypeParameters().map((p) => p.getName())
    };

    // 分析继承信息 - 接口不需要分析继承信息
    const inheritance: InheritanceInfo = this.analyzeInheritanceInfo(interfaceDecl);

    // 分析自己的属性
    const ownProperties = this.analyzeOwnProperties(interfaceDecl, [], generics.parameters);

    // 属性分类
    const propertyClassification = this.classifyProperties(ownProperties, inheritance, generics.parameters);

    return {
      className: interfaceName,
      sourceFilePath,
      originalInterface: interfaceDecl,
      generics,
      inheritance,
      ownProperties,
      inheritedProperties: propertyClassification.inheritedProperties,
      overriddenProperties: propertyClassification.overriddenProperties,
      properties: propertyClassification.properties,
    };
  }

  /**
   * 分析类的继承信息
   * @param cls 类声明
   * @returns 继承信息对象
   */
  private static analyzeInheritanceInfo(cls: ClassDeclaration | InterfaceDeclaration): InheritanceInfo {
    const heritageClaus = cls.getHeritageClauses();
    Logger.debug(
      `分析类的继承信息: ${cls.getName()} ${heritageClaus.length} ${heritageClaus.map(c => c.getText()).join(',')}`);
    for (const clause of heritageClaus) {
      const token = clause.getToken();
      // 接口实现
      if (token !== SyntaxKind.ExtendsKeyword) {
        continue;
      }
      const typeNode = clause.getTypeNodes()[0]; // 继承关系只能继承一个类或者接口

      const className = typeNode.getExpression().getText();
      const args = typeNode.getTypeArguments();
      Logger.debug(`继承信息: text: ${className} getTypeArguments: ${args.map(type => type.getText()).join(', ')}`);
      const classDecl = CustomTypeAnalyzer.getInstance().findClassDeclFromClassName(className, cls.getSourceFile());
      if (!classDecl) {
        throw new CustomError(`class ${className} decl does not exist ${cls.getName} implement ${className}`,
          ErrorCodes.CLASS_DECLARATION_NOT_FOUND);
      }
      if (classDecl instanceof InterfaceDeclaration) {
        const baseClassAnalysis = this.analyzeInterface(classDecl);
        return {
          isInherited: true,
          baseClassAnalysis,
          genericTypeArguments: args
        };
      } else {
        const baseClassAnalysis = this.analyzeClass(classDecl);
        return {
          isInherited: true,
          baseClassAnalysis,
          genericTypeArguments: args
        };
      }

    }
    return { isInherited: false };
  }

  /**
   * 分析类的构造函数参数
   * @param classDecl 类声明
   * @param inheritanceInfo 继承信息
   * @returns 构造函数参数数组
   */
  private static analyzeConstructorParameters(
    classDecl: ClassDeclaration,
    inheritanceInfo?: InheritanceInfo
  ): ConstructorParam[] {
    // 1. 首先检查当前类是否有显式构造函数
    const constructors = classDecl.getConstructors();

    if (constructors.length > 0) {
      // 当前类有显式构造函数，直接分析
      return this.extractConstructorParams(constructors[0]);
    }

    // 2. 当前类没有显式构造函数，查找继承链
    if (inheritanceInfo && inheritanceInfo.isInherited) {
      const baseClassAnalysis = inheritanceInfo.baseClassAnalysis as ClassAnalysis;
      // 递归查找父类的构造函数
      return this.analyzeConstructorParameters(
        baseClassAnalysis.originalClass!,
        baseClassAnalysis.inheritance
      );
    }

    // 3. 整个继承链都没有构造函数，返回空数组
    return [];
  }

  /**
   * 解析@Serializable装饰器选项
   * @param decorator 装饰器节点
   * @returns 可序列化选项
   */
  private static parseSerializableOptions(decorator?: Decorator): SerializableOptions | undefined {
    if (!decorator) {
      return undefined;
    }
    const args = decorator.getArguments();
    let generateSendable: boolean | undefined;
    let _with: string | undefined;
    let deserializationMode: DeserializationMode | undefined;

    const firstArg = args[0];

    if (!firstArg) {
      return {};
    }

    // 处理对象形式：@Serializable({ generateSendable: true })
    if (firstArg.getKind() === SyntaxKind.ObjectLiteralExpression) {
      const properties = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression).getProperties();

      for (const prop of properties) {
        if (prop.getKind() === SyntaxKind.PropertyAssignment) {
          const propAssignment = prop.asKindOrThrow(SyntaxKind.PropertyAssignment);
          const propertyName = propAssignment.getName();
          const initializer = propAssignment.getInitializer();
          if (propertyName === 'generateSendable' && initializer) {
            if (initializer.getKind() === SyntaxKind.TrueKeyword) {
              generateSendable = true;
            } else if (initializer.getKind() === SyntaxKind.FalseKeyword) {
              generateSendable = false;
            }
          } else if (propertyName === 'with' && initializer) {
            // 处理 with 参数，存储完整的表达式文本
            _with = initializer.getText();
          } else if (propertyName === 'deserializationMode' && initializer) {
            // 处理 deserializationMode 参数：'performance' | 'strict'
            const modeText = initializer.getText().replace(/['"]/g, ''); // 去掉引号
            if (modeText === DeserializationMode.PERFORMANCE || modeText === DeserializationMode.STRICT) {
              deserializationMode = modeText as DeserializationMode;
            }
          }
        }
      }
    }
    return { with: _with, generateSendable, deserializationMode };
  }

  /**
   * 解析@SerialName装饰器选项
   * @param decorator 装饰器节点
   * @returns 序列化名称
   */
  private static parseSerialNameOptions(decorator?: Decorator): string | undefined {
    if (!decorator) {
      return undefined;
    }
    const args = decorator.getArguments();
    if (args.length === 0) {
      return undefined;
    }

    const firstArg = args[0];

    // 处理对象形式：@SerialName({ name: 'xxx' })
    if (firstArg.getKind() === SyntaxKind.ObjectLiteralExpression) {
      const properties = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression).getProperties();

      for (const prop of properties) {
        if (prop.getKind() === SyntaxKind.PropertyAssignment) {
          const propAssignment = prop.asKindOrThrow(SyntaxKind.PropertyAssignment);
          const name = propAssignment.getName();

          if (name === 'name') {
            const initializer = propAssignment.getInitializer();
            if (initializer && initializer.getKind() === SyntaxKind.StringLiteral) {
              const stringLiteral = initializer.asKindOrThrow(SyntaxKind.StringLiteral);
              return stringLiteral.getLiteralValue();
            }
          }
        }
      }
    }

    return undefined;
  }

  /**
   * 分析类自身的属性
   * @param cls 类声明
   * @param constructorParams 构造函数参数
   * @param genericParameters 泛型参数
   * @returns 属性分析数组
   */
  private static analyzeOwnProperties(
    cls: ClassDeclaration | InterfaceDeclaration,
    constructorParams: ConstructorParam[],
    genericParameters: string[]
  ): PropertyAnalysis[] {
    const ownProperties: PropertyAnalysis[] = [];
    const props = cls.getProperties();
    for (const prop of props) {
      const propertyAnalysis: PropertyAnalysis = this.createPropertyAnalysis(
        prop,
        constructorParams,
        genericParameters
      );

      // 检测 UNKNOWN 类型
      if (propertyAnalysis.type.kind === PropertyKind.UNKNOWN) {
        const hasTransient = propertyAnalysis.decorators?.isTransient;
        const hasCustomSerializer = !!propertyAnalysis.decorators?.with;

        if (!hasTransient && !hasCustomSerializer) {
          if (prop instanceof PropertyDeclaration) {
            // 未知类型且没有 @Transient 或自定义序列化器，抛出清晰错误
            throw new CustomError(
              `不支持的类型 '${propertyAnalysis.type.sourceText}' 用于属性 '${propertyAnalysis.name
              }' (类: ${cls.getName()})。\n` +
              `请选择以下任一解决方案：\n` +
              `  1. 添加 @Transient() 跳过序列化（属性仍会参与 Sendable 转换和对象拷贝）：\n` +
              `     @Transient()\n` +
              `     ${propertyAnalysis.name}: ${propertyAnalysis.type.sourceText};\n\n` +
              `  2. 添加 @Serializable({with: CustomSerializer}) 指定自定义序列化器：\n` +
              `     @Serializable({with: DateSerializer.INSTANCE})\n` +
              `     ${propertyAnalysis.name}: ${propertyAnalysis.type.sourceText};`,
              ErrorCodes.TYPE_NOT_SUPPORT
            );
          } else {
            // 未知类型且没有 @Transient 或自定义序列化器，抛出清晰错误
            throw new CustomError(`不支持的类型 '${propertyAnalysis.type.sourceText}' 用于属性 '${propertyAnalysis.name
            }' (接口: ${cls.getName()})`, ErrorCodes.TYPE_NOT_SUPPORT);
          }
        }
      }

      // 保留所有属性（包括 UNKNOWN 类型），生成阶段再筛选
      ownProperties.push(propertyAnalysis);
    }
    return ownProperties;
  }

  /**
   * 对属性进行分类，区分继承属性、重写属性和自有属性
   * @param ownProperties 自有属性数组
   * @param inheritance 继承信息
   * @param currentClassGenericParams 当前类的泛型参数列表
   * @returns 分类后的属性对象
   */
  private static classifyProperties(
    ownProperties: PropertyAnalysis[],
    inheritance: InheritanceInfo,
    currentClassGenericParams: string[] = []
  ): {
    inheritedProperties: PropertyAnalysis[];
    overriddenProperties: PropertyAnalysis[];
    properties: PropertyAnalysis[];
  } {
    if (!inheritance.isInherited || !inheritance.baseClassAnalysis) {
      // 没有继承，所有属性都是自有属性
      return {
        inheritedProperties: [],
        overriddenProperties: [],
        properties: [...ownProperties]
      };
    }

    // 递归收集所有祖先属性 - 传递泛型参数进行替换
    const allAncestorProperties = this.collectAllAncestorProperties(
      inheritance.baseClassAnalysis,
      inheritance.genericTypeArguments || [], // 传递子类指定的泛型参数
      currentClassGenericParams // 传递当前类的泛型参数列表
    );

    // 构建自有属性名称集合，用于快速查找重写
    const ownPropertyNames = new Set(ownProperties.map((prop) => prop.name));

    // 分类祖先属性：被重写的 vs 继承的
    const inheritedProperties: PropertyAnalysis[] = [];

    for (const ancestorProp of allAncestorProperties) {
      if (!ownPropertyNames.has(ancestorProp.name)) {
        // 被当前类继承了
        inheritedProperties.push(ancestorProp);
      }
    }

    // 确定当前类中的重写属性
    const overriddenProperties = ownProperties.filter((prop) =>
      allAncestorProperties.some((ancestorProp) => ancestorProp.name === prop.name)
    );

    // 合并最终属性：继承的 + 当前类的（重写优先）
    const properties = [...inheritedProperties, ...ownProperties];

    return {
      inheritedProperties,
      overriddenProperties,
      properties
    };
  }

  /**
   * 递归收集所有祖先类的属性，并进行泛型替换
   * @param classAnalysis 类分析结果
   * @param childGenericArguments 子类泛型参数
   * @param currentClassGenericParams 当前类的泛型参数列表
   * @returns 所有祖先属性数组
   */
  private static collectAllAncestorProperties(
    classAnalysis: ClassAnalysis | InterfaceAnalysis,
    childGenericArguments: TypeNode[] = [],
    currentClassGenericParams: string[] = []
  ): PropertyAnalysis[] {
    const allProperties: PropertyAnalysis[] = [];

    // 1. 构建泛型替换映射
    const parentGenericParams = classAnalysis.generics.parameters || [];
    const genericMapping = GenericTypeSubstitutionUtil.buildGenericMapping(parentGenericParams, childGenericArguments);

    // 2. 对父类自有属性进行泛型替换
    const substitutedProperties = classAnalysis.ownProperties.map((property) =>
      GenericTypeSubstitutionUtil.substitutePropertyType(property, genericMapping, currentClassGenericParams)
    );

    allProperties.push(...substitutedProperties);

    // 3. 递归处理更上层祖先，传递泛型参数
    if (classAnalysis.inheritance.isInherited && classAnalysis.inheritance.baseClassAnalysis) {
      // 关键修复: 需要解析父类的泛型参数，将其中的泛型引用替换为当前映射的具体类型
      const parentGenericTypeArgs = classAnalysis.inheritance.genericTypeArguments || [];

      // 对父类的泛型参数进行替换，解决泛型参数引用问题
      // 例如: CrudRepository<T> extends Repository<T, number>
      // 这里的 T 需要替换为当前映射中的 UserEntity
      const resolvedParentGenericArgs = parentGenericTypeArgs.map(typeArg => {
        // 解析类型参数为 TypeStructure
        const typeStructure = TypeHandlerRegistry.getInstance().parseType(typeArg, {
          depth: 0,
          genericParams: parentGenericParams // 使用父类的泛型参数上下文
        });

        // 如果是泛型引用,进行替换
        if (typeStructure.kind === PropertyKind.GENERIC && genericMapping.has(typeStructure.sourceText)) {
          return genericMapping.get(typeStructure.sourceText)!;
        }

        // 否则保持原样
        return typeArg;
      });

      Logger.debug(`[CollectAncestors] Resolved parent generic args: ${resolvedParentGenericArgs.map(a => a.getText()).join(', ')}`);

      const ancestorProperties = this.collectAllAncestorProperties(
        classAnalysis.inheritance.baseClassAnalysis,
        resolvedParentGenericArgs, // 传递解析后的泛型参数
        currentClassGenericParams // 保持传递当前类的泛型参数
      );
      allProperties.push(...ancestorProperties);
    }

    return allProperties;
  }

  /**
   * 提取构造函数参数信息
   * @param constructor 构造函数声明
   * @returns 构造函数参数数组
   */
  private static extractConstructorParams(constructor: ConstructorDeclaration): ConstructorParam[] {
    const parameters: ConstructorParam[] = [];

    for (const param of constructor.getParameters()) {
      parameters.push({
        name: param.getName(),
        type: param.getTypeNodeOrThrow().getText(),
        isOptional: param.hasQuestionToken(),
        defaultValue: param.hasInitializer() ? param.getInitializerOrThrow().getText() : undefined
      });
    }

    return parameters;
  }

  /**
   * 创建属性分析对象
   * @param prop 属性声明
   * @param constructorParams 构造函数参数
   * @param genericParameters 泛型参数
   * @returns 属性分析对象
   */
  private static createPropertyAnalysis(
    prop: PropertyDeclaration | PropertySignature,
    constructorParams: ConstructorParam[],
    genericParameters: string[]
  ): PropertyAnalysis {
    const name = prop.getName();
    let typeNode = prop.getTypeNode();
    if (!typeNode) {
      typeNode = this.analyzePropertyType(prop);
    }

    if (!typeNode) {
      throw new CustomError(`无法分析属性 '${name}' 的类型。请检查属性声明。`, ErrorCodes.TYPE_NOT_SUPPORT);
    }

    const defaultValue: string | undefined = prop instanceof PropertyDeclaration ?
      this.analyzeDefaultValue(prop, constructorParams) : undefined;
    const decorators = prop instanceof PropertyDeclaration ? this.analyzePropertyDecorators(prop) : undefined;
    const type = TypeHandlerRegistry.getInstance().parseType(typeNode, { genericParams: genericParameters, depth: 0 });
    type.isOptional = prop.hasQuestionToken();

    // 检测属性可见性修饰符
    const visibility: PropertyVisibility =
      prop.hasModifier(SyntaxKind.PrivateKeyword) ? PropertyVisibility.PRIVATE :
        prop.hasModifier(SyntaxKind.ProtectedKeyword) ? PropertyVisibility.PROTECTED :
          PropertyVisibility.PUBLIC;

    const constructorParam = constructorParams.find((param) => param.name === name);

    // 计算构造函数参数的可选性（用于后续验证）
    const isParamOptional = constructorParam
      ? constructorParam.isOptional ||
      constructorParam.defaultValue !== undefined ||
      this.hasUndefinedInUnion(constructorParam.type)
      : true;

    let isMust: boolean;
    if (constructorParam) {
      // 属性在构造函数参数中，以构造函数参数的必要性为准
      // 构造函数参数可选的条件：
      // 1. 有显式的?标记（isOptional为true）
      // 2. 有默认值
      // 3. 类型字符串中包含undefined作为联合类型成员
      isMust = !isParamOptional;
    } else {
      // 属性不在构造函数中，判断属性本身的必要性
      isMust = decorators?.isRequired || !this.isOptional(prop, defaultValue, type);
    }

    // @Transient 属性的构造函数参数验证
    // 检查构造函数参数是否可选或有默认值
    if (decorators?.isTransient && constructorParam && !isParamOptional) {
      throw new CustomError(
        `@Transient 属性 '${name}' 的构造函数参数必须是可选的或有默认值。\n` +
        `因为 @Transient 属性不参与序列化，反序列化时无法从外部数据获取值。\n` +
        `请修改构造函数参数为以下任一形式：\n` +
        `  1. 可选参数: constructor(..., ${name}?: ${constructorParam.type})\n` +
        `  2. 带默认值: constructor(..., ${name}: ${constructorParam.type} = defaultValue)`,
        ErrorCodes.TRANSIENT_ATTR_OPTIONAL
      );
    }

    return {
      name,
      defaultValue,
      decorators,
      type,
      isMust,
      visibility
    };
  }

  private static analyzePropertyType(prop: PropertyDeclaration | PropertySignature): TypeNode | undefined {
    const name = prop.getName();
    let typeNode = prop.getTypeNode();

    // 如果已经能获取到类型节点，则直接返回
    if (typeNode) {
      return typeNode;
    }

    Logger.warn(`无法获取属性${name}的类型，使用typeChecker方式获取类型`);
    let type = TsMorphUtil.getTypeChecker().getTypeAtLocation(prop);
    let typeText = type.getText();

    Logger.warn(`typeChecker方式获取类型: ${typeText} `);

    // 处理 import('...').Type 格式
    typeText = this.simplifyImportType(typeText);

    // 如果类型是 any，尝试通过初始化器获取更具体的类型
    if (typeText === 'any') {
      const result = this.getTypeFromInitializer(prop, name);
      if (result) {
        return result;
      }
    }

    // 如果仍然无法确定类型，则抛出异常
    if (typeText === 'any') {
      throw new CustomError(`无法获取属性${name}的类型，需要显示声明`, ErrorCodes.TYPE_NOT_SUPPORT);
    }

    Logger.info(`使用typeChecker方式获取类型成功: ${typeText}`);
    prop.setType(typeText);
    return prop.getTypeNode();
  }

  /**
   * 简化 import('...').Type 格式的类型名称
   * @param typeText 完整的类型文本
   * @returns 简化后的类型名称
   */
  private static simplifyImportType(typeText: string): string {
    // 匹配 import('...').Type 或 import("...").Type 模式
    const importPattern = /import\s*\(\s*['"][^'"]*['"]\s*\)\.(.+)/;
    const match = typeText.match(importPattern);

    if (match) {
      // 返回简化后的类型名称
      return match[1];
    }

    // 如果不是 import 形式，返回原类型名
    return typeText;
  }

  private static getTypeFromInitializer(prop: PropertyDeclaration | PropertySignature,
    propName: string): TypeNode | undefined {
    const initializer = prop.getInitializer();
    if (!initializer) {
      return undefined;
    }

    Logger.warn(`无法获取属性${propName}的类型，使用初始化器获取类型: ${initializer.getText()}`);
    const initializerType = TsMorphUtil.getTypeChecker().getTypeAtLocation(initializer);
    let typeText = initializerType.getText();
    Logger.warn(`使用初始化器获取类型: ${typeText}`);

    if (typeText !== 'any') {
      prop.setType(typeText);
      return prop.getTypeNode();
    }


    if (initializer.getKind() !== SyntaxKind.NewExpression) {
      return undefined;
    }

    const newExpression = initializer as NewExpression;
    const expression = newExpression.getExpression();
    if (!expression) {
      return undefined;
    }

    const exprText = expression.getText();
    const supportedTypes = ['Map', 'Set', 'WeakMap', 'WeakSet', 'Array', 'Object', 'ArrayList', 'HashMap', 'HashSet',
      'LinkedList', 'Decimal', 'List'];

    if (!supportedTypes.includes(exprText)) {
      return undefined;
    }

    // 获取完整的类型参数信息
    const typeArgs = newExpression.getTypeArguments();
    if (typeArgs.length > 0) {
      typeText = `${exprText}<${typeArgs.map(arg => arg.getText()).join(', ')}>`;
    } else {
      typeText = exprText;
    }

    prop.setType(typeText);
    return prop.getTypeNode();
  }

  /**
   * 判断属性是否为可选属性
   * @param node 属性声明节点
   * @param defaultValue 默认值
   * @param type 类型结构
   * @returns 是否为可选属性
   */
  private static isOptional(node: PropertyDeclaration | PropertySignature, defaultValue: string | undefined,
    type: TypeStructure): boolean {
    // 1. 语法上带 ?（prop?: T, param?: T）
    if (node.hasQuestionToken()) {
      return true;
    }

    // 2. 有默认值（不管是定义属性声明的还是构造函数形参中定义的）
    if (defaultValue !== undefined) {
      return true;
    }

    // 3. 类型是undefined或者是 T | undefined
    if (type.kind === PropertyKind.UNDEFINED || type.kind === PropertyKind.OPTIONAL) {
      return true;
    }

    // 4. 联合类型判断
    if (
      type.kind === PropertyKind.UNION &&
      type.unionDetails &&
      type.unionDetails.some((member) => member.kind === PropertyKind.UNDEFINED)
    ) {
      return true;
    }

    return false;
  }

  /**
   * 分析属性的默认值
   * @param prop 属性声明
   * @param constructorParams 构造函数参数
   * @returns 默认值字符串
   */
  private static analyzeDefaultValue(
    prop: PropertyDeclaration,
    constructorParams: ConstructorParam[]
  ): string | undefined {
    // 1. 优先构造函数默认值
    const param = constructorParams.find((item) => item.name === prop.getName());
    if (param && param.defaultValue) {
      return param.defaultValue;
    }

    // 2. 声明的默认值
    if (prop.hasInitializer()) {
      return prop.getInitializerOrThrow().getText();
    }

    return undefined;
  }

  /**
   * 检查类型字符串是否包含undefined作为联合类型成员
   * @param typeText 类型字符串
   * @returns 是否包含undefined作为联合类型成员
   */
  private static hasUndefinedInUnion(typeText: string): boolean {
    // 移除所有空白字符
    const normalized = typeText.replace(/\s/g, '');

    // 如果类型字符串本身就是undefined
    if (normalized === 'undefined') {
      return true;
    }

    // 分割联合类型，但要考虑泛型中的嵌套
    const parts = this.splitUnionType(normalized);

    // 检查是否有部分恰好是undefined
    return parts.some(part => part === 'undefined');
  }

  /**
   * 分割联合类型，考虑泛型、数组、括号等嵌套结构
   * @param typeText 标准化后的类型字符串（无空格）
   * @returns 联合类型的各个部分
   */
  private static splitUnionType(typeText: string): string[] {
    const parts: string[] = [];
    let current = '';
    let depth = 0; // 跟踪<>、[]、()的嵌套深度

    for (let i = 0; i < typeText.length; i++) {
      const char = typeText[i];

      if (char === '<' || char === '[' || char === '(') {
        depth++;
        current += char;
      } else if (char === '>' || char === ']' || char === ')') {
        depth--;
        current += char;
      } else if (char === '|' && depth === 0) {
        // 只在顶层分割联合类型
        if (current) {
          parts.push(current);
          current = '';
        }
      } else {
        current += char;
      }
    }

    if (current) {
      parts.push(current);
    }

    return parts;
  }

  /**
   * 分析属性装饰器
   * @param prop 属性声明
   * @returns 属性装饰器对象
   */
  private static analyzePropertyDecorators(prop: PropertyDeclaration): PropertyDecorators {
    const decorators = prop.getDecorators();
    let isRequired: boolean = false;
    let isTransient: boolean = false;
    let isPlainValue: boolean = false;
    let serialName: string | undefined;
    let _with: string | undefined;

    decorators.forEach((decorator) => {
      const name = decorator.getName();

      switch (name) {
        case DecoratorConstants.SERIAL_NAME:
          serialName = this.parseSerialNameOptions(decorator);
          break;
        case DecoratorConstants.REQUIRED:
          isRequired = true;
          break;
        case DecoratorConstants.TRANSIENT:
          isTransient = true;
          break;
        case DecoratorConstants.PLAIN_VALUE:
          isPlainValue = true;
          break;
        case DecoratorConstants.SERIALIZABLE:
          _with = this.parseSerializableOptions(decorator)!.with;
      }
    });

    // 注解互斥检查：@Transient 与其他序列化注解互斥
    if (isTransient) {
      const conflictingDecorators: string[] = [];
      if (isRequired) {
        conflictingDecorators.push('@Required');
      }
      if (serialName) {
        conflictingDecorators.push('@SerialName');
      }
      if (_with) {
        conflictingDecorators.push('@Serializable');
      }
      if (isPlainValue) {
        conflictingDecorators.push('@PlainValue');
      }

      if (conflictingDecorators.length > 0) {
        throw new CustomError(
          `属性 '${prop.getName()}' 的注解冲突：@Transient 与 ${conflictingDecorators.join(', ')} 不能同时使用。\n` +
          `@Transient 表示跳过序列化，与其他序列化配置注解互斥。\n` +
          `请移除 @Transient 或移除其他序列化注解。`,
          ErrorCodes.ANNOTATION_CONFLICT
        );
      }
    }

    // 注解互斥检查：@PlainValue 与自定义序列化器互斥
    if (isPlainValue && _with) {
      throw new CustomError(
        `属性 '${prop.getName()}' 的注解冲突：@PlainValue 与 @Serializable(with:) 不能同时使用。\n` +
        `@PlainValue 跳过类型转换直接使用原始值，与自定义序列化器冲突。\n` +
        `请移除 @PlainValue 或移除自定义序列化器。`,
        ErrorCodes.ANNOTATION_CONFLICT
      );
    }

    return {
      isRequired,
      isTransient,
      isPlainValue,
      serialName,
      with: _with
    };
  }
}